package dao.impl;

import bean.Admin;
import dao.AdminDao;
import util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class AdminDaoImpl implements AdminDao {

    Connection con = null;

    Admin admin = null;

    PreparedStatement ps = null;

    ResultSet rs = null;

    int row = 0;

    /***
     * 管理员登录
     * @param username
     * @param password
     * @return
     */
    @Override
    public Admin login(String username, String password) {
        try {
            con = JdbcUtil.getCon();
            String sql = "select * from admin where username = ? and password = ?";
            ps = con.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            rs = ps.executeQuery();
            if (rs.next()) {
                admin = new Admin();
                admin.setUid(rs.getString("uid"));
                admin.setUsername(rs.getString("username"));
                admin.setPassword(rs.getString("password"));
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                JdbcUtil.close(rs,ps,con);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return admin;
    }

    /***
     * 注册账号
     * @param admin
     * @return
     */
    @Override
    public int addAdmin(Admin admin) {
        try {
            con = JdbcUtil.getCon();
            String sql = "insert into admin values(?,?,?)";
            ps = con.prepareStatement(sql);
            ps.setString(1,admin.getUid());
            ps.setObject(2,admin.getUsername());
            ps.setObject(3,admin.getPassword());
            row = ps.executeUpdate();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                JdbcUtil.close(rs,ps,con);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return row;
    }
}
